<?php
/**
 * | 节程 [ 节程赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 *  | Copyright (c) 2020~2029 温州惊蛰网络科技有限公司 All rights reserved.
 * +----------------------------------------------------------------------
 *  | Licensed 节程并不是自由软件，未经许可不能去掉节程相关版权
 * +----------------------------------------------------------------------
 */
declare (strict_types=1);

namespace app\index\model;

use app\SearchModel;
use think\facade\Db;
use think\Model;
use app\utils\Addons;
use app\utils\SendMsg;
use think\model\concern\SoftDelete;


class UserCoupon extends BaseModel
{
    use SoftDelete;

    protected $globalScope = ['mallId'];

    public function __construct(array $data = [])
    {
        parent::__construct($data);
        if (isset($data['status'])) {
            self::append(['status_text']);
        }
    }

    public function getStatusTextAttr($value, $data)
    {
        $status = [
            0 => '未使用',
            1 => '已使用',
            2 => '过期'
        ];
        return $status[$data['status']];
    }

    public function coupon()
    {
        return $this->hasOne(Coupon::class, 'id', 'coupon_id');
    }

    public function merchant()
    {
        return $this->belongsTo(Merchant::class, 'merchant_id', 'id')
            ->bind(['merchant_name' => 'name', 'merchant_logo' => "logo", 'merchant_is_self' => "is_self"]);
    }

    public static function giveUserCoupon($couponId, $user_id)
    {
        $coupon = Db::name('coupon')->where(['id' => $couponId])->lock(true)->find();
        if (!$coupon) {
//            throw new Exception('优惠券不存在', HTTP_NOTACCEPT);
            return false;
        }
        $coupon = (object)($coupon);
        if ($coupon->total_limit_type == 1 && $coupon->total_limit <= $coupon->used) {
            Db::name('coupon')->update(['status' => 2], ['id' => $couponId]);
            return false;
//            throw new Exception('优惠券不足', HTTP_NOTACCEPT);
        }

        if ($coupon->user_limit_type == 1) {
            $userCouponList = Db::name('coupon')->where(['user_id' => $user_id, 'coupon_id' => $couponId])
                ->select()->toArray();
            if ($coupon->user_limit < sizeof($userCouponList) + 1) {
                return false;
            }
//                throw new Exception('超过限领', HTTP_NOTACCEPT);
        }

        Db::name('user_coupon')->insert(
            [
                'user_id' => $user_id,
                'coupon_id' => $couponId,
                'merchant_id' => $coupon->merchant_id,
                'used_type' => $coupon->used_type,
                'mall_id' => $coupon->mall_id
            ]
        );
        Db::name('coupon')->where(['id' => $couponId])->inc("used", 1)->update();

        $check = Addons::check($coupon->mall_id, 4);

        if ($check) {
            $user = Db::name("user")->find($user_id);
            $msgData = array(
                'mall_name' => MallBase::getBase(),
                'coupon_user' => $user['nickname'],
                'coupon_name' => $coupon->name,
                'coupon_validity' => $coupon->time_limit_type == 0 ?
                    "有效期至: " . date("Y-m-d H:i:s", strtotime("+" . $coupon->limit_time . " day")) :
                    "有效期至: " . $coupon->limit_indate_end,
                'coupon_time' => date("Y-m-d H:i:s")
            );

            $sendMsg = new SendMsg("优惠券发放通知");
            $mid = $coupon->mall_id;
            try {
                $url = !empty($user->UserWx->type) && $user->UserWx->type == 1 ?
                    request()->domain() . "/pages/conpon/conpon?type=0&mall_id=".$mid :
                    request()->domain() . "/h5/#/pages/conpon/conpon?type=0&mall_id=".$mid;

                $sendMsg->send($user, $msgData, $url);
            } catch (Exception $e) {

            }
        }
    }

}
